<template>
    <div class="Notice">
        <div class="horseeBox" id="horseBox">
            <ul class="messageList" id="messageList">
                <li class="messageItem" :style="{width: listItemWidth}"></li>
                <li
                    class="messageItem"
                    v-for="(item, index) in messageList"
                    :key="item.id"
                    @mouseover="mouseOver"
                    @mouseleave="mouseLeave"
                    @click="handlePageJumpDetail(item, index)"
                >{{ (index + 1) + '、' + item.noticeTitle }}</li>
            </ul>
        </div>
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="noticeDetailShow"
            append-to-body
            center
            @close="dialogClose"
            width="700px"
            class="noticeBody"
        >
            <div slot="title" class="noticeTitle">{{noticeDetailObj.noticeTitle}}</div>
            <div class="noticeUser">
                <span style="margin-right: 12px;">创建人 : {{noticeDetailObj.createUser}}</span>
                <span>发布时间 : {{noticeDetailObj.publishTime}}</span>
            </div>
            <div style="margin-top: 12px;text-align: justify;" class="ql-editor">
                <span v-html="noticeDetailObj.noticeContent"></span>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button
                    @click="dialogClose(noticeDetailObj)"
                    type="primary"
                    v-if="noticeDetailObj.isRead === '0'"
                >知道了</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { isEmptyObject } from '@/utils/Object';
export default {
    name: 'Notice',
    data() {
        return {
            // 跑马灯数据
            horseRaceLamp: [

            ],
            messageList: [],
            listItemWidth: 0,
            noticeDetailShow: false,
            noticeDetailObj: {},
            itemList: [],
            index: 0,
            intervalId: null,
        }
    },
    computed: {
        ...mapGetters([
            'noticeData', // 最新公告
            'userInfo',
            'queueObj',//队列信息更新
        ])
    },
    warch: {
        noticeData(newValue, oldValue) {
            if (newValue) {
                this.messageList = newValue;
                if (newValue.length > 0) {
                    this.getHorseRaceLamp();
                }
            }
        },
    },
    mounted() {
        // 每隔30秒 调用一次这个事件
        // setInterval(this.getNoticeData(),30000);
        this.getComingTableDate();
        this.getQueueInitData();
        this.getNoticeData(); //加载数据函数
        this.dataRefreh();
    },
    methods: {
        // 获取 公告数据
        getNoticeData() {
            console.log('公告——获取数据1234');
            const params = {
                pageNum: 1,
                pageSize: 5,
            };
            this.$post.noticeMangage.searchByUserId(params)
                .then((res) => {
                    if (res.data.success) {
                        this.messageList = res.data.content.recordList || [];
                        this.getHorseRaceLamp();
                    }
                });
        },
        // 获取 宽度问题
        getHorseRaceLamp() {
            const list = document.getElementById('messageList');
            const horseBox = document.getElementById('horseBox');
            this.listItemWidth = `${horseBox.offsetWidth}px`;
            this.$nextTick(() => {
                this.itemList = document.getElementsByClassName('messageItem');
                let ListWidth = 0;
                for (let i = 0; i < this.itemList.length; i++) {
                    ListWidth += this.itemList[i].offsetWidth;
                    // console.log(itemList[i].offsetWidth, 'offsetWidth---' + i)
                }
                list.style.width = `${ListWidth + 2}px`;
                const time = `${Math.round(ListWidth / 50)}s`;
                list.classList.add('animation');
                list.style.animationDuration = time;
            });

            // this.editKeyFrames('houseAnimation', ListWidth)
            // list.style.animationTimingFunction = 'linear'
            // list.style.animationIterationCount = 'infinite'
            //     //console.log(time, '动画时间')
        },
        // 点击公告弹出公告详情
        handlePageJumpDetail(row, index) {
            this.noticeDetailShow = true;
            this.index = index;
            this.noticeDetailObj = JSON.parse(JSON.stringify(row));
        },
        // 鼠标移入暂停动画
        mouseOver() {
            if (!this.noticeDetailShow) {
                const list = document.getElementById('messageList');
                // console.log(document.getElementById('messageList').offsetLeft)
                list.style.animationPlayState = 'paused';
                const { offsetLeft } = list;
                list.style.left = `${offsetLeft}px`;
            }
        },
        // 鼠标离开 继续进行动画
        mouseLeave() {
            if (!this.noticeDetailShow) {
                const list = document.getElementById('messageList');
                list.style.animationPlayState = 'running';
            }
        },

        // 查找 keyframes 动画
        findKeyframs(animName) {
            const res = [];
            let rule;
            const styleSheet = document.styleSheets;
            for (let i = 0; i < styleSheet.length; i++) {
                for (let x = 0; x < styleSheet[i].cssRules.length; x++) {
                    rule = styleSheet[i].cssRules[x];
                    if (rule.type === window.CSSRule.KEYFRAMES_RULE) {
                        console.log(rule, `rules    ${i}-${x}`);
                    }
                    if (rule.name && rule.name.split('-')[0] === animName) {
                        res.push({
                            rule,
                            animName: rule.name,
                        });
                    }
                }
            }
            return res;
        },

        // 修改动画
        editKeyFrames(animName, width) {
            const keyframes = this.findKeyframs(animName);
            const horseeBox = `${width - (document.body.offsetWidth / 2)}px`;
            console.log(horseeBox);
            keyframes[0].rule.appendRule('0% { left : 0%; }');
            keyframes[0].rule.appendRule(`100% { left : -${horseeBox}; }`);
            keyframes[1].rule.appendRule('0% { left : 0%; }');
            keyframes[1].rule.appendRule(`100% { left : -${horseeBox}; }`);
            document.getElementById('messageList').style.animationName = keyframes[0].animName;
        },
        // 弹框关闭，动画继续
        dialogClose(data) {
            const list = document.getElementById('messageList');
            list.style.animationPlayState = 'running';
            if (data) {
                const params = {
                    id: data.id,
                    isRead: '1',
                };
                this.$post.noticeMangage.updateDeptUserNotice(params)
                    .then((res) => {
                        if (res.data.success) {
                            this.noticeDetailShow = false;
                            this.messageList[this.index].isRead = '1';
                            this.$store.commit('common/UPDATE_NOTICEDATA', this.messageList);
                            this.getHorseRaceLamp();
                        }
                    });
            }
        },
        // 定时刷新数据函数
        dataRefreh() {
            // 计时器正在进行中，退出函数
            if (this.intervalId != null) {
                return;
            }
            // 计时器为空，操作
            this.intervalId = setInterval(() => {
                this.getNoticeData(); //加载数据函数
                this.getComingTableDate();
                this.getQueueInitData();
            }, 30000);
        },
        // 停止定时器
        clear() {
            clearInterval(this.intervalId); //清除计时器 
            this.intervalId = null; //设置为null
        },
        // 获取当前坐席 的所有接班信息
        getComingTableDate() {
            let parent = {
                name: this.userInfo.userAccount,
            };
            this.$post.information.findMyHandover(parent).then((res) => {
                if (res.data.success) {
                    // this.onComingTableDate = res.data.content;
                    console.log('接班数据', res.data.content);
                    // this.ComingNum = res.data.content.length
                    this.$store.dispatch('menu/updatedSetPickerList', res.data.content)
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        // 队列数据
        getQueueInitData() {
            // const userInfo = JSON.parse(getToken());
            let data = {
                userAccount: this.userInfo.userAccount,
                userName: this.userInfo.userName,
                ctiNum: this.userInfo.ctiNum,
            };
            this.$post.kpi.getMonitorData(data)
                .then((res) => {
                    if (res.data.success) {
                        // this.queueNum = res.data.content.queueNum;
                        // this.busyNum = res.data.content.busyNum;
                        console.log('队列数据', res.data.content);
                        // this.answerRate = (res.data.content.answerRate * 100).toFixed(0);
                        const queueObjss = res.data.content;
                        if (isEmptyObject(this.queueObj)) {
                            this.$store.dispatch('menu/updatedSetQueue', queueObjss)
                        } else {
                            const queueObjArray = Object.keys(this.queueObj);
                            for (let index = 0; index < queueObjArray.length; index++) {
                                const element = queueObjArray[index];
                                if (this.queueObj[element] !== queueObjss[element]) {
                                    this.$store.dispatch('menu/updatedSetQueue', queueObjss)
                                    return false;
                                }
                            }
                        }

                    } else {
                        this.$message.error(res.data.msg);
                    }
                });
        },
    },
    destroyed() {
        // 在页面销毁后，清除计时器
        this.clear();
    },
}
</script>
<style scoped lang="scss">
.Notice {
    position: relative;
    height: 40px;

    .noticeTitle {
        text-align: center;
        font-size: 22px;
        font-weight: 600;
    }
    .noticeUser {
        text-align: right;
        padding-bottom: 12px;
        color: #999;
        border-bottom: 1px solid #f6f6f6;
    }
    .notice {
        line-height: 32px;
        font-size: 12px;
    }
    .horseeBox {
        position: absolute;
        left: 0px;
        bottom: 0px;
        width: 100%;
        box-sizing: border-box;
        background-color: #f2f6f9;
        overflow: hidden;
        z-index: 10;
        border-radius: 5px;
    }
    .horseeBox:hover {
        cursor: pointer;
    }
    .messageList {
        white-space: nowrap;
        position: relative;
        // display: flex;

        .messageItem {
            float: left;
            padding: 0 10px;
            height: 38px;
            line-height: 40px;
            list-style: none;
            letter-spacing: 1px;
            font-size: 12px;
            color: #ff2d2d;
        }
    }
    .animation {
        animation: houseAnimation linear normal infinite;
    }
}
@keyframes houseAnimation {
    0% {
        transform: perspective(0px) translate3d(0px, 0px, 0px);
    }
    100% {
        transform: perspective(0px) translate3d(-100%, 0px, 0px);
    }
}
</style>